var fun1 = require('./ruleWin');
const Websocket = require('ws')
// 启动一个websocket服务
const ws = new Websocket.Server({
    port: 8887
})
var viewer=[]; //观众数组
var plays=[]; //玩家数组
const clients = []; //连接数组
// 封装一个群发方法
const sendAll = (data) => {
    for(let e of plays){
        e.client.send(JSON.stringify(data))
    }
} 

// 发送给其他玩家
const sendOther=(id,data)=>{
    for(let e of plays){
        if(e.id!=id){
            e.client.send(JSON.stringify(data));
        }
    }
}
// 发送给观众
const sendViewer =(data)=>{
    console.log(data,"data")
    for(let e of viewer){
        e.client.send(JSON.stringify(data))
    }
}

var chessboard=new Array(225).fill(null);
var playState=1;
var nextPlay="black"; //第一步为黑棋先走,然后变为白棋
var firstPlay="black"
var nextPlayId=""; //第一次为先进来的用户,走棋后轮换
function checkWinner(index) {
    return fun1.ruleWin(chessboard, index)
    
}
function init(params) {

}

// 监听客户端的连接
ws.on('connection',(client,req) => {
    // 保存当前连接上的客户端
    const ip = req.socket.remoteAddress;
    const id=Math.random();
    const isPlayer=plays.length<=1?true:false;
    client.id=id;
    let isReady=false;
    if(plays.length<=1){
        plays.push({client,ip,id,isReady,status:""})
    }else{
        viewer.push({client,ip,id});
    }
    clients.push({client,ip,id,isReady})
    let data={
        plays,
        clients,
        isOne:true,
        playState,
        id,
        isPlayer,
        status:"",
        chessboard,
        nextPlay,
        nextPlayId
    }
    client.send(JSON.stringify(data))
    data.isOne=false;
    
    // 当玩家人满了后 
    if(viewer.length<=0){
        sendAll(data);
    }
        
    
   

    // 监听客户端发来的消息
    client.on('message',(res) => {
        const {id,index,status,type,isReady}=JSON.parse(res)
        if(type && type=="again"){
            sendOther(id,{
                status,
                playState:4    //再来一次
            })
            sendViewer({status,playState})
        }else if(type =="againOk"){ //同意再来一次
            sendOther(id,{
                type:"ok",
                playState:5  
            })
            sendViewer({
                type:"ok",
                playState:5  
            })
            chessboard=new Array(225).fill(null)  //初始化棋盘
            nextPlay="black",
            plays.forEach((item,index)=>{
                if(item.status==firstPlay){
                    if(item.status=="black"){
                        firstPlay="white"
                    }else{
                        firstPlay="black" 
                    }                   
                }else{
                    nextPlayId=item.id
                }
            })
            sendAll({
                nextPlayId,
                nextPlay:firstPlay,
                playState:2,
                overReady:true,
                plays
            })
            sendViewer({
                nextPlayId,
                nextPlay:firstPlay,
                playState:2,
                overReady:true,
                plays
            })
        }else if(type =="againNo"){
            sendOther(id,{
                type:"no",
                playState:5  
            })
        }else if(type=="ready"){
            plays.find(item=>item.id==id).isReady=isReady
            clients.find(item=>item.id==id).isReady=isReady;

            let overReady=plays.every(item=>item.isReady==true) && plays.length==2
            if(overReady ){
                // 分配棋色
                var num = Math.floor(Math.random() * 10) + 1;
                if(num<=5){
                    plays[0].status="black";
                    plays[1].status="white";
                    nextPlayId=plays[0].id
                }else{
                    plays[0].status="white";
                    plays[1].status="black";
                    nextPlayId=plays[1].id
                }
            }
            sendAll({playState:2,id,isReady,plays,clients,overReady,nextPlayId});
            sendViewer({playState:2,id,isReady,plays,clients,overReady,nextPlayId})
        }else if(type=="playing"){
            if(id==nextPlayId){
                chessboard[index]=status
                playState=3;
                plays.forEach((item)=>{
                    if(item.id!=id){
                        nextPlayId=item.id;
                        nextPlay=item.status
                    }
                })
                let winner=checkWinner(index)
                sendAll({
                    index,
                    nextPlay,
                    nextPlayId,
                    status,
                    playState,
                    winner
                })
                sendViewer({
                    index,
                    nextPlay,
                    nextPlayId,
                    status,
                    playState,
                    winner
                })
            }
        }
        
        // 
        
    })

    // 监听客户端断开
    client.on('close',(req,bbb) => {
        // arr.splice(1,1)
        let arr=JSON.parse(JSON.stringify(plays))
        plays.forEach(function(item,index){
            if(item.id==client.id){
                arr.splice(index,1)
                chessboard=new Array(225).fill(null)
                nextPlayId="";
               
                arr[0].status=""
                nextPlay="black"
                arr.splice(index,1)
                arr[0].status="";
                arr[0].isReady=false
                sendAll({
                    playState:6,
                    plays:arr,
                    nextPlayId,
                    nextPlay
                })
                sendViewer({
                    playState:6,
                    plays:arr,
                    nextPlayId,
                    nextPlay
                })   
            }    
        })
        plays=arr
        viewer.forEach(function(item,index){
            if(item.id==client.id){
                viewer.splice(index,1)
            }
        })
    })
})